package com.jp.knowledge.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.zxing.client.android.CaptureActivity;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.JpMainActivity;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.activity.NetLogActivity;
import com.jp.knowledge.activity.PayActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.logic.ShareLogic;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.ContactsActivity;
import com.jp.knowledge.my.activity.MyReeceActivity;
import com.jp.knowledge.my.activity.MyRoleActivity;
import com.jp.knowledge.my.activity.MyVieCoinActivity;
import com.jp.knowledge.my.activity.MyVipActivity;
import com.jp.knowledge.my.activity.OrganizeActivity;
import com.jp.knowledge.my.activity.PcImportActivity;
import com.jp.knowledge.my.activity.QrCodeActivity;
import com.jp.knowledge.my.activity.SetActivity;
import com.jp.knowledge.my.activity.UserSettingActivity;
import com.jp.knowledge.my.adapter.MyDataAdapter;
import com.jp.knowledge.my.adapter.MyMoreAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.business.MyMainBusiness;
import com.jp.knowledge.my.business.Vector;
import com.jp.knowledge.my.model.ActiveDataModel;
import com.jp.knowledge.my.model.OptionSelectModel;
import com.jp.knowledge.my.view.RoundRectView;
import com.jp.knowledge.my.view.ShareInvitePw;
import com.jp.knowledge.util.ImageLoadUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by jiayen on 16/9/28.
 */
public class MyFragmentold extends BaseFragment implements View.OnClickListener {

    //退出登录
    public static final int EXIT_LOGIN_CODE = 0x0000000000111;
    //登录
    public static final int LOGIN_CODE = 0x0000000000112;

    public static final int SWITCH_ORGANIZE_CODE = 0x0000000000113;

    public static final int USER_DATA_SETTING = 0x0000000000114;

    @ViewInject(R.id.my_lly_header)
    private LinearLayout personInfo;

    @ViewInject(R.id.my_iv_header)
    private ImageView mHeaderIv;

    @ViewInject(R.id.my_tv_user)
    private TextView mUserTv;

    @ViewInject(R.id.my_round_v_message)
    private RoundRectView mMessageRoundV;

    @ViewInject(R.id.my_iv_grade)
    private ImageView mGradeIv;

    @ViewInject(R.id.my_tv_grad)
    private TextView mGradeTv;

    @ViewInject(R.id.my_rv_more)
    private RecyclerView mMoreRv;

    @ViewInject(R.id.my_rv_data)
    private RecyclerView mDataRv;

    @ViewInject(R.id.my_tv_role)
    private TextView mRoleTv;

    @ViewInject(R.id.my_tv_organize)
    private TextView mOrganizeTv;

    @ViewInject(R.id.my_tv_organize_state)
    private TextView mOrganizeTvState;

    @ViewInject(R.id.my_tv_organize_state_ll)
    private LinearLayout mOrganizeTvStateLl;

    @ViewInject(R.id.my_tv_franchise)
    private TextView mFranchiseTv;

    @ViewInject(R.id.my_rv_attestation)
    private RecyclerView mAttestationRv;

    @ViewInject(R.id.my_tv_share)
    private TextView mShareTv;

    @ViewInject(R.id.my_round_v_share)
    private RoundRectView mShareRoundV;

    @ViewInject(R.id.my_iv_message)
    private ImageView  msgText;

    @ViewInject(R.id.my_tv_message)
    private TextView  msg;

    @ViewInject(R.id.my_tv_achievement)
    private TextView  aviment;//成就

    @ViewInject(R.id.my_lly_role)
    private LinearLayout  myRole;//竞品管家

    @ViewInject(R.id.my_lly_organize)
    private LinearLayout  orignazation;//组织

    @ViewInject(R.id.my_lly_help)
    private LinearLayout  help;//帮助

    @ViewInject(R.id.my_lly_share)
    private LinearLayout  share;//分享

    @ViewInject(R.id.my_lly_set)
    private LinearLayout  setLayout;//设置

    private MyMainBusiness mBusiness = new MyMainBusiness();
    boolean isLogin = false;// 模拟登录状态
    private View mView;
    private UserData userData;
    private PersonLogic personLogic;
    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;
    private List<OptionSelectModel> attestationRvData;

    private ShareLogic shareLogic;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.activity_my_main_old, null);
        x.view().inject(this, mView);
        initHead(mView);
        init();
        return mView;
    }



    protected void init() {

        shareLogic = new ShareLogic(mContext, new ShareBoardlistener() {
            @Override
            public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                if(snsPlatform.mShowWord.equals("share_copy_url")){
                        ToasUtil.toast(mContext, "复制成功");
                }else {
                    try {
                        ShareAction shareAction = new ShareAction((Activity) mContext).withText("分享个人信息").withTitle("竞品说")
                                .withTargetUrl(userData.getPortrait())
                                .setPlatform(share_media)
                                .setCallback(shareLogic.umShareListener);
                        if (!share_media.equals(SHARE_MEDIA.SINA)) {//新浪分享图片会失败暂时还不知道是什么原因
                            shareAction.withMedia(new UMImage(mContext,userData.getPortrait()));
                        }
                        shareAction.share();
                    }catch (Exception e){}
                }
            }
        });

        personLogic = new PersonLogic(mContext, new PersonLogic.UserDataCallBack() {
            @Override
            public void done(UserData data) {
                userData = data;
                if (userData != null && userData.getIsLogin() == 1) {
                    isLogin = true;
                    initOthers(true);
                } else {
                    isLogin = false;
                    initOthers(false);
                }
            }
        });

        initBroadCast();
        initIsLogin();
        initTitle();
        initOthers(isLogin);
        initMoreRv(mBusiness.getMoreItems());

        initClickListener();//初始化事件
    }

    /**
     * 初始化事件
     */
    private void initClickListener() {
        msgText.setOnClickListener(this);
        msg.setOnClickListener(this);
        mHeaderIv.setOnClickListener(this);
        mGradeIv.setOnClickListener(this);
        mGradeTv.setOnClickListener(this);
        aviment.setOnClickListener(this);
        mFranchiseTv.setOnClickListener(this);
        myRole.setOnClickListener(this);
        orignazation.setOnClickListener(this);
        help.setOnClickListener(this);
        share.setOnClickListener(this);
        setLayout.setOnClickListener(this);
    }

    /**
     * 初始化本地广播通知
     */
    private void initBroadCast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(LocalBroadCast.GET_LOGIN_INFO)) {
                    isLogin = true;
                    initOthers(isLogin);
                }
            }
        });
        IntentFilter intent = new IntentFilter();
        intent.addAction(LocalBroadCast.GET_LOGIN_INFO);
        localBroadcastManager.registerReceiver(localBroadCast, intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localBroadCast);
    }

    private void initIsLogin() {
        userData = application.getUserData();
        if (userData == null) {//先获取个人信息
            personLogic.getUserData();
        } else if (userData.getIsLogin() == 1) {//处于登录状态
            isLogin = true;
        } else {
            isLogin = false;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.my_iv_message:// 消息
            case R.id.my_tv_message:
                // 登录：查看用户信息；未登录：跳转至登录页
                startActivity(new Intent(mContext, PayActivity.class));
                break;
            case R.id.my_iv_header:// 头像
            case R.id.my_tv_user:// 用户名
                // 登录：查看用户信息；未登录：跳转至登录页
                startActivityForResult(new Intent(mContext, UserSettingActivity.class), USER_DATA_SETTING);
                break;
            case R.id.my_iv_grade:// 级别
            case R.id.my_tv_grad:
                if (isLogin)
                    startActivity(new Intent(mContext, MyVipActivity.class));
                else
                    startActivity(new Intent(mContext, LoginActivity.class));
                break;
            case R.id.my_tv_achievement:// 成就
                break;
            case R.id.my_tv_franchise:// 特权
                break;
            case R.id.my_lly_role:// 角色
                startActivity(new Intent(mContext, MyRoleActivity.class));
                break;
            case R.id.my_lly_organize:// 组织
                if(!application.isLogin()){
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    startActivityForResult(new Intent(mContext, OrganizeActivity.class),
                            SWITCH_ORGANIZE_CODE);
                }
                break;
            case R.id.my_lly_help:// 帮助
                showNetLog();
                break;
            case R.id.my_lly_share:// 分享
               shareLogic.share();
                break;
            case R.id.my_lly_set:// 设置
                startActivityForResult(new Intent(mContext, SetActivity.class), EXIT_LOGIN_CODE);
                break;
        }
    }

    private void initTitle() {
        topName.setText(R.string.my_tv_main);
        topName.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
        topDesc.setVisibility(View.GONE);
        leftIcon.setVisibility(View.GONE);
        rightIcon.setVisibility(View.GONE);
    }

    private void initDataRv(List<ActiveDataModel> list) {
        mDataRv.setLayoutManager(new LinearLayoutManager(
                mContext, LinearLayoutManager.HORIZONTAL, false));
        MyDataAdapter mDataAdapter = new MyDataAdapter(mContext, list);
        mDataAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                switch (position) {
                    case 0:
                        startActivity(new Intent(mContext, MyVieCoinActivity.class));
                        break;
                }
            }
        });
        mDataRv.setAdapter(mDataAdapter);
    }

    private void initAttestationRv(List<OptionSelectModel> list) {
        mAttestationRv.setHasFixedSize(true);
        mAttestationRv.setLayoutManager(new LinearLayoutManager(
                mContext, LinearLayoutManager.HORIZONTAL, false));
        MyMoreAdapter mMoreAdapter = new MyMoreAdapter(mContext, new ArrayList<OptionSelectModel>());
        mMoreAdapter.updateAdapter(attestationRvData);
        mMoreAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                try {
                    startActivity(new Intent(mContext, Class.forName(attestationRvData.get(position).mValue)));
                } catch (Exception e){
                    return;
                }
            }
        });
        mAttestationRv.setAdapter(mMoreAdapter);
    }

    private void initMoreRv(List<OptionSelectModel> list) {
        mMoreRv.setHasFixedSize(true);
        mMoreRv.setLayoutManager(new LinearLayoutManager(
                mContext, LinearLayoutManager.HORIZONTAL, false));
        MyMoreAdapter mMoreAdapter = new MyMoreAdapter(mContext, list);
        mMoreAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                switch (position) {
                    case 0://收藏
                        if(application.isLogin())
                            ToasUtil.toast(mContext, "功能调整中，请后续版本在试该功能");
//                            startActivity(new Intent(context, CollectionActivity.class));
                        else
                            startActivity(new Intent(mContext, LoginActivity.class));
                        break;
                    case 1:// 红包
                        startActivity(new Intent(mContext, MyReeceActivity.class));
                        break;
                    case 2:// 档案
                        startActivity(new Intent(mContext, UserSettingActivity.class));
                        break;
                    case 3:// 扫一扫
                        startActivityForResult(new Intent(mContext, CaptureActivity.class),10001);
                        break;
                }
            }
        });
        mMoreRv.setAdapter(mMoreAdapter);
    }

    private void initOthers(boolean isLogin) {
        userData = application.getUserData();
        if (userData == null)
            isLogin = false;
        else if (userData.getIsLogin() == 1) isLogin = true;
        else isLogin = false;
        if (isLogin) {
            topName.setVisibility(View.VISIBLE);
            personInfo.setVisibility(View.VISIBLE);
            mUserTv.setText(userData == null ? "未知" : userData.getUsername());
            mUserTv.setTextColor(Color.WHITE);
            mFranchiseTv.setVisibility(View.VISIBLE);
            ImageLoadUtil.loadCircle(mContext, userData == null ? "" : userData.getPortrait(), mHeaderIv);

            mGradeIv.setImageResource(R.mipmap.novice);
            mGradeTv.setText("初级管家");
            mRoleTv.setText("竞品说管家");
            topName.setVisibility(View.VISIBLE);
        } else {
            topName.setVisibility(View.GONE);
            personInfo.setVisibility(View.GONE);
            mGradeIv.setImageResource(R.mipmap.sign_in);
            mGradeTv.setText("登录");
            topName.setVisibility(View.GONE);
        }

        attestationRvData = mBusiness.getAttestationItems(userData);
        initAttestationRv(attestationRvData);
        setOrganizeMessage(isLogin);
        initDataRv(mBusiness.getActiveData(getActiveIndex(isLogin),userData));
    }

    /**
     * @return 假定用户活跃数据数据量
     */
    private List<Integer> getActiveIndex(boolean isLogin) {
        List<Integer> index = new ArrayList<>();
        index.add(isLogin&&userData!=null ? userData.getIntegralNum() : 0);         // 我的竞币
        index.add(isLogin&&userData!=null ? userData.getBrowseNum() : 0);           // 我的足迹
        index.add(isLogin&&userData!=null ? userData.getSubscribetNum() : 0);       // 关注数
        index.add(isLogin&&userData!=null ? userData.getFollowNum() : 0);           // 收藏数
        index.add(isLogin&&userData!=null ? userData.getSubjectNum() : 0);          // 主题数
        index.add(isLogin&&userData!=null ? userData.getTopicNum() : 0);            // 话题数
        index.add(isLogin&&userData!=null ? userData.getAdvicesNum() : 0);          // 报料数
        index.add(isLogin&&userData!=null ? userData.getExpNum() : 0);              // 体验数
        index.add(isLogin&&userData!=null ? userData.getShareNum() : 0);            // 分享数
        return index;
    }

    /* 设置所属组织显示信息 */
    private void setOrganizeMessage(boolean isLogin){
        if(isLogin && userData != null && userData.getCompanyName() != null) {
            String companyText = userData.getCompanyName();
            mOrganizeTv.setText(companyText);

            if(userData.getAuditStete() == 0 && userData.getCompanyManage() == 0 && userData.getCompanyState() == 0) {
                mOrganizeTvState.setText("请认证企业");
                mOrganizeTvState.setTextColor(mContext.getResources().getColor(R.color.red));
                mOrganizeTvStateLl.setVisibility(View.VISIBLE);
            } else if(userData.getAuditStete() == 0 && userData.getCompanyManage() == 0 && userData.getCompanyState() == 1) {
                mOrganizeTvState.setText("加入审核中");
                mOrganizeTvState.setTextColor(mContext.getResources().getColor(R.color.red));
                mOrganizeTvStateLl.setVisibility(View.VISIBLE);
            } else if(userData.getAuditStete() == 0 && userData.getCompanyManage() == 0 && userData.getCompanyState() == 2) {
                mOrganizeTvState.setText("企业认证中");
                mOrganizeTvState.setTextColor(mContext.getResources().getColor(R.color.red));
                mOrganizeTvStateLl.setVisibility(View.VISIBLE);
            } else if(userData.getAuditStete() == 0 && userData.getCompanyManage() == 1 && userData.getCompanyState() == 0) {
                mOrganizeTvState.setText("请认证企业");
                mOrganizeTvState.setTextColor(mContext.getResources().getColor(R.color.red));
                mOrganizeTvStateLl.setVisibility(View.VISIBLE);
            } else if(userData.getAuditStete() == 0 && userData.getCompanyManage() == 1 && userData.getCompanyState() == 1) {
                mOrganizeTvStateLl.setVisibility(View.GONE);
            } else if(userData.getAuditStete() == 0 && userData.getCompanyManage() == 1 && userData.getCompanyState() == 2) {
                mOrganizeTvState.setText("企业认证中");
                mOrganizeTvState.setTextColor(mContext.getResources().getColor(R.color.red));
                mOrganizeTvStateLl.setVisibility(View.VISIBLE);
            } else if(userData.getAuditStete() == 1 && userData.getCompanyManage() == 0 && userData.getCompanyState() == 0) {
                mOrganizeTvStateLl.setVisibility(View.GONE);
            } else if(userData.getAuditStete() == 1 && userData.getCompanyManage() == 0 && userData.getCompanyState() == 1) {
                mOrganizeTvState.setText("认证企业");
                mOrganizeTvState.setTextColor(mContext.getResources().getColor(R.color.gray_deep));
                mOrganizeTvStateLl.setVisibility(View.VISIBLE);
            } else if(userData.getAuditStete() == 1 && userData.getCompanyManage() == 0 && userData.getCompanyState() == 2) {
                mOrganizeTvStateLl.setVisibility(View.GONE);
            } else if(userData.getAuditStete() == 1 && userData.getCompanyManage() == 1 && userData.getCompanyState() == 0) {
                mOrganizeTvStateLl.setVisibility(View.GONE);
            } else if(userData.getAuditStete() == 1 && userData.getCompanyManage() == 1 && userData.getCompanyState() == 1) {
                mOrganizeTvState.setText("认证企业");
                mOrganizeTvState.setTextColor(mContext.getResources().getColor(R.color.gray_deep));
                mOrganizeTvStateLl.setVisibility(View.VISIBLE);
            } else if(userData.getAuditStete() == 1 && userData.getCompanyManage() == 1 && userData.getCompanyState() == 2) {
                mOrganizeTvStateLl.setVisibility(View.GONE);
            }

            attestationRvData = mBusiness.getAttestationItems(userData);
            ((MyMoreAdapter)mAttestationRv.getAdapter()).updateAdapter(attestationRvData);
            mAttestationRv.setVisibility(View.VISIBLE);
        } else {
//            mOrganizeTv.setText(R.string.organize_no_join);
            mOrganizeTv.setText("");
            mAttestationRv.setVisibility(View.GONE);
            mOrganizeTvStateLl.setVisibility(View.GONE);
        }
    }

    /**
     * 邀请对话框选项监听
     */
    ShareInvitePw.OnOptionSelectListener mOnInviteSelect = new ShareInvitePw.OnOptionSelectListener() {
        @Override
        public void quoteClick(int position) {
            switch (position) {
                case 0:// 手机通讯录
                    Intent companyIntent = new Intent(mContext, ContactsActivity.class);
                    companyIntent.putExtra(Vector.TRANSFER_INTEGER + "contacts_type",
                            ContactsActivity.CONTACTS_PHONE);
                    startActivity(companyIntent);
                    break;
                case 3:// 二维码邀请
                    Intent intent = new Intent(mContext, QrCodeActivity.class);
                    intent.putExtra(Vector.TRANSFER_INTEGER + "qr_scan_type",
                            QrCodeActivity.QR_CODE_ORGANIZE);
                    startActivity(intent);
                    break;
                default:
                    ToasUtil.toast(mContext, "选中：" + position);
                    break;
            }
        }

        @Override
        public void systemClick(int position) {
            switch (position) {
                case 0:// 电脑端导入
                    startActivity(new Intent(mContext, PcImportActivity.class));
                    break;
                default:
                    ToasUtil.toast(mContext, "选中：" + position);
                    break;
            }
        }
    };

    /**
     * 分享对话框选项监听
     */
    ShareInvitePw.OnOptionSelectListener mOnShareSelect = new ShareInvitePw.OnOptionSelectListener() {
        @Override
        public void quoteClick(int position) {
            switch (position) {
                default:
                    ToasUtil.toast(mContext, "选中：" + position);
                    break;
            }
        }

        @Override
        public void systemClick(int position) {
            ToasUtil.toast(mContext, "选中：" + position);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == EXIT_LOGIN_CODE && resultCode == EXIT_LOGIN_CODE) {
            isLogin = false;
            initOthers(isLogin);
        } else if (requestCode == LOGIN_CODE) {//登录成功
        } else if(requestCode==10001 && resultCode==10001){//二维码返回
            String url = data.getStringExtra("url");
            ToasUtil.toast(mContext,url);
        } else if(requestCode == SWITCH_ORGANIZE_CODE && resultCode == RESULT_OK){
            setOrganizeMessage(isLogin);
        } else if(requestCode == USER_DATA_SETTING && resultCode == RESULT_OK){
            initOthers(isLogin);
        }
    }

    /* 查看网络请求日志 */
    private void showNetLog(){
        startActivity(new Intent(getContext(), NetLogActivity.class));
    }
}
